package net.studou.service;

import java.lang.reflect.Field;

import javax.servlet.http.HttpSession;

import net.studou.annotation.VerifyCodeAnnotation;
import net.studou.exception.SystemException;
import net.studou.exception.VerifyCodeException;

import org.springframework.stereotype.Component;

@Component("verifyCodeService")
public class VerifyCodeService {

	public <T> T verifyCode(T vo, HttpSession session) throws VerifyCodeException  {
		Field[] fields = vo.getClass().getDeclaredFields();
		for (Field field : fields) {
			if (field.isAnnotationPresent(VerifyCodeAnnotation.class)) {
				field.setAccessible(true);
				String code = null;
				try {
					code = field.get(vo).toString();
				} catch (Exception e) {
					throw new SystemException("System error");
				}
				String sessionCode = (String) session.getAttribute("validateCode");
				session.removeAttribute("validateCode");
				if (code == null || !code.equalsIgnoreCase(sessionCode)) {
					throw new VerifyCodeException("Validate code error");
				}
				break;
			}
		}
		return vo;
	}
}
